<template>
    <div>
        <div class="table-title">
            <h3>论文审批</h3>
        </div>
        <div class="user-show">
            <div class="user-table">
                <div class="user-table-utils">
                    <div>
                        <el-input placeholder="请输入查询内容" v-model="searchContent" class="input-with-select">
                            <el-select v-model="searchItem" slot="prepend" placeholder="请选择查询项">
                                <el-option v-for="item in searchItems" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                            <el-button slot="append" icon="el-icon-search" @click="handleSearch" />
                        </el-input>
                    </div>
                    <div>
                        <el-button type="success" icon="el-icon-check" @click="handleExam('pass')">审批通过</el-button>

                        <el-button type="danger" icon="el-icon-close" @click="handleExam('back')">驳回审批</el-button>
                    </div>
                </div>
                <el-table :data="tableData" border style="width: 100%" v-loading="tableLoading"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55">
                    </el-table-column>
                    <el-table-column prop="thesisId" label="论文编号">
                    </el-table-column>
                    <el-table-column prop="name" label="论文课题">
                    </el-table-column>
                    <el-table-column prop="thesis" label="论文">
                        <template slot-scope="scope">
                            <el-tooltip class="item" effect="dark" :content="scope.row.filename" placement="top">
                                <el-button type="text" @click="downloadThesis(scope.row.filename)">{{ scope.row.thesis ?
                                    "下载论文" : "" }}</el-button>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column prop="author" label="著作人">
                    </el-table-column>
                    <el-table-column prop="press" label="出版社">
                    </el-table-column>
                    <el-table-column prop="examed" label="审批状态">
                        <template slot-scope="scope">
                            <div slot="reference" class="name-wrapper">
                                <el-tag v-if="scope.row.examed === '已审批'" size="medium">{{ scope.row.examed }}</el-tag>
                                <el-tag v-else size="medium" type="warning">{{ scope.row.examed }}</el-tag>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="time" label="发行时间">
                    </el-table-column>
                    <el-table-column prop="updateTime" label="更新时间">
                    </el-table-column>
                </el-table>
                <div class="user-pagination">
                    <el-pagination background small layout="prev, pager, next" :total="pagination.total"
                        :page-size="pagination.pageSize" :current-page="pagination.current"
                        @current-change="handleCurrentChange" />
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import apis from '@/utils/api';
import request from '@/utils/requestMethod';
import { Message } from 'element-ui';
import './style.less';
import axios from 'axios';

export default {
    name: 'thesisExam',
    mounted() {
        this.fetchThesis();
    },
    data() {
        return {
            tableLoading: false,
            tableData: [],
            searchItem: '',
            searchItems: [
                {
                    label: '全部',
                    value: 'all'
                },
                {
                    label: '论文编号',
                    value: 'thesisId'
                },
                {
                    label: '论文课题',
                    value: 'name'
                },
                {
                    label: '著作人',
                    value: 'author'
                },
                {
                    label: '出版社',
                    value: 'press'
                }
            ],
            searchContent: '',
            ifSearch: false,
            pagination: {
                current: 1,
                pageSize: 10,
                total: 0
            },
            multipleSelection: []
        }
    },
    methods: {
        /**
         *  获取所有论文信息
         */
        fetchThesis() {
            this.tableLoading = true;
            const {
                pagination: {
                    current,
                    pageSize
                }
            } = this;

            const userInfo = JSON.parse(localStorage.getItem('userInfo'));
            const teacher = userInfo.name;

            const body = {
                current,
                pageSize,
                teacher
            }

            request(apis.getWillExamThesis, {
                method: 'POST',
                body
            }).then(res => {
                const {
                    objects,
                    total
                } = res.data;

                this.pagination.total = total;
                this.tableData = objects;
            }).finally(() => {
                this.tableLoading = false;
            }).catch(() => {
                this.tableLoading = false;
            })
        },

        /**
         * 处理翻页事件
         */
        handleCurrentChange(value) {
            this.pagination.current = value;
            if (this.ifSearch) {
                this.handleSearch();
            } else {
                this.fetchThesis();
            }
        },

        /**
         *  处理搜索事件
         */
        handleSearch() {
            this.ifSearch = true;
            const {
                searchItem,
                searchContent,
                pagination: {
                    current,
                    pageSize
                }
            } = this;

            if (searchItem === 'all') {
                this.fetchThesis();
                this.searchContent = '';
                this.searchItem = '';
                this.ifSearch = false;
            } else {
                if (searchItem === '') {
                    Message.warning('请输入搜索项');
                }
                if (searchContent === '') {
                    Message.warning('请输入搜索内容');
                }
            }

            if (searchContent !== '' && searchItem !== '' && searchItem !== 'all') {
                let content = searchContent;
                const body = {
                    searchItem,
                    content,
                    current,
                    pageSize
                }
                this.tableLoading = true;
                request(apis.searchThesis, {
                    method: 'POST',
                    body
                }).then(res => {
                    const {
                        objects,
                        message,
                        total
                    } = res.data;

                    this.pagination.total = total;
                    this.tableData = objects;
                    Message.success(message);

                }).finally(() => {
                    this.tableLoading = false;
                }).catch(() => {
                    this.tableLoading = false;
                    Message.error('搜索失败');
                })
            }
        },

        /**
         *  处理选择表格列事件
         */
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },

        /**
         *  处理审批事件
         */
        handleExam(type) {
            const {
                tableData,
                multipleSelection
            } = this;

            if (tableData.length === 0) {
                Message.warning('暂无需要审批的论文');
            } else if (multipleSelection.length === 0) {
                Message.warning('请勾选要进行审批或驳回的论文');
            } else {
                this.tableLoading = true;
                multipleSelection.forEach(item => {
                    switch (type) {
                        case 'back':
                            item.examed = '已驳回';
                            break;
                        case 'pass':
                            item.examed = '已通过';
                            break;
                        default:
                            break;
                    }
                });

                const body = {
                    examList: multipleSelection
                }
                request(apis.hadnleExam, {
                    method: 'POST',
                    body
                }).then(res => {
                    const {
                        objects,
                        message
                    } = res.data;

                    if (objects === multipleSelection.length) {
                        Message.success(message);
                        this.fetchThesis();
                    } else {
                        Message.warning('部分论文审批未成功');
                    }
                }).finally(() => {
                    this.tableLoading = false;
                }).catch(err => {
                    this.tableLoading = false;
                    Message.warning(err);
                })
            }
        },
        downloadThesis(value) {
            console.log(value);
            axios({
                method: 'GET',
                url: '/api' + apis.downloadThesis,
                params: {filename: value},
                responseType: 'blob'
            }).then(response => {
                // 创建一个 blob 对象，并创建 URL 对象
                const blob = new Blob([response.data]);
                const url = window.URL.createObjectURL(blob);
                // 创建 a 标签并设置下载链接并模拟点击
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', value);
                document.body.appendChild(link);
                link.click();
                // 删除临时对象
                URL.revokeObjectURL(url);
                document.body.removeChild(link);
            }).catch(() => {
                this.$message.error('下载失败，请重试！')
            });
        }
    }
}
</script>